package com.oa.demo.common.configure;


import com.oa.demo.common.entity.BaseConstant;
import com.oa.demo.common.entity.BaseResponse;
import com.oa.demo.common.utils.OaUtils;
import feign.RequestInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * feign调用 请中的权限信息要跟着带往跳转后的请求地址上
 * @author 孔德成
 * @date 2020/11/24 18:20
 */
public class OAuth2FeignConfigure {

    /**
     * 转发时增加请求头参数
     * @return
     */
    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor() {
        return requestTemplate -> {
            // 添加 Zuul Token
            String zuulToken = new String(Base64Utils.encode(BaseConstant.GATEWAY_TOKEN_VALUE.getBytes()));
            requestTemplate.header(BaseConstant.GATEWAY_TOKEN_HEADER, zuulToken);

            Object details = SecurityContextHolder.getContext().getAuthentication().getDetails();
            if (details instanceof OAuth2AuthenticationDetails) {
                String authorizationToken = ((OAuth2AuthenticationDetails) details).getTokenValue();
                requestTemplate.header(HttpHeaders.AUTHORIZATION, "bearer " + authorizationToken);
            }
        };
    }
    /**
     * 校验请求头参数
     * @return
     */
    @Bean
    public HandlerInterceptor serverProtectInterceptor(){
        // 从请求头中获取 Zuul Token
        return new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                // 从请求头中获取  Token
                String token = request.getHeader(BaseConstant.GATEWAY_TOKEN_HEADER);
                String gatewayToken = new String(Base64Utils.encode(BaseConstant.GATEWAY_TOKEN_VALUE.getBytes()));
                // 校验 Zuul Token的正确性
                if (StringUtils.equals(gatewayToken, token)) {
                    return true;
                } else {
                    BaseResponse baseResponse = new BaseResponse();
                    OaUtils.makeResponse(
                            response, MediaType.APPLICATION_JSON_VALUE,
                            HttpServletResponse.SC_FORBIDDEN,
                            baseResponse.message("请通过网关请求资源"));
                    return false;
                }
            }
        };
    }

}
